/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mti.javashare.webservices;

import com.mti.javashare.beans.User;
import com.mti.javashare.dao.IUserDao;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author Toto
 */
@WebService(endpointInterface = "com.mti.javashare.webservices.IUserWebService")
public class UserWebService implements IUserWebService
{
    @Autowired
    private IUserDao dao;
    
    @Override
   public int add(String username, String pass)
   {
       User user = new User();
       user.setUsername(username);
       user.setPassword(encryptPassword(pass));
       dao.add(user);
       return user.getId();
   }

    @Override
    public void update(int id, String username, String pass)
    {
        User user = dao.getById(id);
        user.setUsername(username);
        user.setPassword(encryptPassword(pass));
        dao.update(user);
    }

    @Override
    public void remove(int id)
    {
      User user = dao.getById(id);
      dao.remove(user);
    }

    @Override
    public User getById(int id)
    {
        return dao.getById(id);
    }

    @Override
    public User getByName(String username)
    {
        return dao.getByName(username);
    }

    @Override
    public Collection<User> getAll()
    {
        return dao.getAll();
    }

    @Override
    public void addFriend(int id1, int id2)
    {
        User user1 = dao.getById(id1);
        User user2 = dao.getById(id2);
        user1.getFriends().add(user2);
        user2.getFriends().add(user1);
        dao.update(user1);
        dao.update(user2);
    }

    @Override
    public void removeFriend(int id1, int id2)
    {
        User user1 = dao.getById(id1);
        User user2 = dao.getById(id2);
        user1.getFriends().remove(user2);
        user2.getFriends().remove(user1);
        dao.update(user1);
        dao.update(user2);
    }

    @Override
    public Collection<User> getFriends(int id)
    {
        User user = dao.getById(id);
        return user.getFriends();
    }
    
    private byte[] encryptPassword(String pass)
    {
        MessageDigest digest; 
        try 
        {
            digest = MessageDigest.getInstance("SHA-512");
        }
        catch (NoSuchAlgorithmException ex)
        {
            return null;
        }
        digest.update(pass.getBytes()); 
        return digest.digest();
    }
}
